/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.core.exception.handler;

import cn.simastudio.talos.common.constants.Modules;
import cn.simastudio.talos.core.constants.MessageCode;
import cn.simastudio.talos.core.exception.base.BaseException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Usage: 默认异常处理类，可以再添加需要处理的异常类型
 *
 * @author Charkey
 * @date 2015/5/14 11:46
 */
@ControllerAdvice
@ResponseBody
public class DefaultExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionHandler.class);

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private LocaleResolver localeResolver;

    @ExceptionHandler({UnauthorizedException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("exception", e);
        mv.setViewName("/jsp/error/401.jsp");
        return mv;
    }

    @ExceptionHandler({UnknownAccountException.class})
    public ModelAndView processUnknownAccountException(NativeWebRequest request, UnknownAccountException e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("exception", e);
        mv.setViewName("/jsp/system/login.jsp");
        return mv;
    }

    @ExceptionHandler({BaseException.class})
    public Object processCaptchaMismatchException(NativeWebRequest request, BaseException e) {
        if (request.getHeader("Accept").contains("application/json")) {
            return e.toString();
        } else {
            // 获取国际化配置文件中code对应的内容，若无相应的code，则抛出NoSuchMessageException；要求：一定要有相应的code配置！
            String localizedMessage = messageSource.getMessage(MessageCode.INTERNAL_SERVER_ERROR, null, localeResolver.resolveLocale((HttpServletRequest) request.getNativeRequest()));
            ModelAndView mv = new ModelAndView();
            mv.addObject("module", Modules.SYSTEM);
            mv.addObject("code", "500");
            mv.addObject("message", localizedMessage);
            mv.setViewName("/jsp/error/general_error.jsp");
            return mv;
        }
    }
}
